package cn.yhbk.web.modules.manager.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.yhbk.web.common.exception.ApiException;
import cn.yhbk.web.modules.manager.Mapper.TbScholarShipTypeMapper;
import cn.yhbk.web.modules.manager.Pojo.DTO.Gpa.GpaDto;
import cn.yhbk.web.modules.manager.Pojo.DTO.ScholarShip.ScholarShipDto;
import cn.yhbk.web.modules.manager.Pojo.DTO.ScholarShip.ScholarShipLimit;
import cn.yhbk.web.modules.manager.Pojo.DTO.ScholarShip.ScholarShipTree;
import cn.yhbk.web.modules.manager.Pojo.Entity.TbMajor;
import cn.yhbk.web.modules.manager.Pojo.Entity.TbScholarShipType;
import cn.yhbk.web.modules.manager.Pojo.Entity.TbScholarship;
import cn.yhbk.web.modules.manager.Mapper.TbScholarshipMapper;
import cn.yhbk.web.modules.manager.Pojo.VO.Scholarship.ScholarShipPag;
import cn.yhbk.web.modules.manager.Pojo.VO.Scholarship.ScholarShipPeople;
import cn.yhbk.web.modules.manager.Pojo.VO.Scholarship.ScholarshipAdd;
import cn.yhbk.web.modules.manager.Service.ITbScholarshipService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 奖学金信息表 服务实现类
 * </p>
 *
 * @author 有何不可
 * @since 2023-08-05
 */
@Slf4j
@Service
public class TbScholarshipServiceImpl extends ServiceImpl<TbScholarshipMapper, TbScholarship> implements ITbScholarshipService {

    @Autowired
    private TbScholarshipMapper tbScholarshipMapper;

    @Autowired
    private TbScholarShipTypeMapper tbScholarShipTypeMapper;

    @Autowired
    private TbMajorServiceImpl majorService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ScholarShipPag getScholarShipPag(Integer currentPage, Integer pageSize, Long typeId, String scholarshipName) {
        ScholarShipPag scholarShipPag = new ScholarShipPag();
        scholarShipPag.setPageSize(pageSize);
        scholarShipPag.setCurrentPage(currentPage);
        scholarShipPag.setTotalPage(tbScholarshipMapper.queryTotalNum(typeId, scholarshipName));
        scholarShipPag.setScholarshipList(tbScholarshipMapper.queryScholarshipPage((currentPage - 1) * pageSize, pageSize, typeId, scholarshipName));
        return scholarShipPag;
    }

    @Override
    public List<ScholarShipTree> getAllScholarShip() {
        List<ScholarShipTree> scholarShipTrees = new ArrayList<>();
        List<TbScholarShipType> tbScholarShipTypes = tbScholarShipTypeMapper.queryScholarShipType();
        for (TbScholarShipType tbScholarShipType: tbScholarShipTypes){
            ScholarShipTree scholarShipTree = new ScholarShipTree();
            BeanUtils.copyProperties(tbScholarShipType, scholarShipTree);
            QueryWrapper<TbScholarship> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type_id", tbScholarShipType.getId());
            scholarShipTree.setChildList(tbScholarshipMapper.selectList(queryWrapper));
            scholarShipTrees.add(scholarShipTree);
        }
        return scholarShipTrees;
    }

    @Override
    public List<GpaDto> getScholarshipSort(List<GpaDto> gpaRecordSort, Long majorId, Long scholarshipId, Long graderId) {
        List<GpaDto> res = new ArrayList<>();
        List<TbScholarship> scholarshipList = tbScholarshipMapper.querySameType(scholarshipId);
        Integer begin = 0;
        Integer end = 0;
        // 查看排序是否一样，一样就不用选择范围
        boolean isSameSort = isSameSort(scholarshipList);
        if (isSameSort){
            end = (Integer) redisTemplate.opsForValue().get("scholarshipId-majorId-gradeId:" + scholarshipId + "-" + majorId + "-" + graderId);
        } else {
            for (TbScholarship tbScholarship : scholarshipList) {
                Integer s = (Integer) redisTemplate.opsForValue().get("scholarshipId-majorId-gradeId:" + tbScholarship.getId() + "-" + majorId + "-" + graderId);
                if (s == null){
                    throw new ApiException("获取获奖人数限制出错，请联系管理员");
                }

                if (tbScholarship.getId().equals(scholarshipId)){
                    end = begin + s;
                    break;
                }
                else{
                    begin += s;
                }
            }
        }


        for (int i = begin; i < end; i++){
            res.add(gpaRecordSort.get(i));
        }

        return res;
    }

    private boolean isSameSort(List<TbScholarship> scholarshipList) {
        return scholarshipList.stream().map(TbScholarship::getSort).distinct().count() == 1;
    }

    @Transactional
    @Override
    public Boolean saveScholarShip(Long adminId, ScholarshipAdd scholarshipAdd) {
        LocalDateTime now = LocalDateTime.now();
        TbScholarship tbScholarship = BeanUtil.copyProperties(scholarshipAdd, TbScholarship.class);
        tbScholarship.setCreateTime(now);
        tbScholarship.setUpdateTime(now);
        tbScholarship.setAdminId(adminId);

        this.baseMapper.insert(tbScholarship);

        return true;
    }

    @Override
    public void updatePeople(ScholarShipPeople scholarShipPeople) {
        redisTemplate.opsForValue().set("scholarshipId-majorId-gradeId:" + scholarShipPeople.getScholarshipId() + "-" + scholarShipPeople.getMajorId() + "-" + scholarShipPeople.getGradeId(),
                scholarShipPeople.getPeople());
        // 删除缓存的排序
        redisTemplate.delete("gpaSort:" + scholarShipPeople.getMajorId() + "-" + scholarShipPeople.getScholarshipId() + "-" + scholarShipPeople.getGradeId());
    }

    @Override
    public List<ScholarShipDto> getAllScholarShipList() {
        return this.baseMapper.queryScholarshipList();
    }

//    @Override
//    public List<ScholarShipLimit> getLimitNum(Long scholarshipId) {
//        List<ScholarShipLimit> res = new ArrayList<>();
//        // 获取所有专业
//        List<TbMajor> list = majorService.list();
//        for (TbMajor tbMajor : list) {
//            ScholarShipLimit scholarShipLimit = new ScholarShipLimit();
//            scholarShipLimit.setMajorId(tbMajor.getId());
//            scholarShipLimit.setMajorName(tbMajor.getMajorName());
//            scholarShipLimit.setNumber(redisTemplate.opsForValue().get("scholarshipId-majorId-gradeId:" + scholarshipId + "-" + tbMajor.getId()));
//            res.add(scholarShipLimit);
//        }
//        return res;
//    }


    @Override
    public List<ScholarShipLimit> getLimitNum(Long majorId, Long graderId) {
        List<ScholarShipLimit> res = new ArrayList<>();
        // 获取所有奖学金
        List<TbScholarship> scholarshipList = this.baseMapper.selectList(new LambdaQueryWrapper<TbScholarship>());
        for (TbScholarship tbScholarship : scholarshipList) {
            Integer s = (Integer) redisTemplate.opsForValue().get("scholarshipId-majorId-gradeId:" + tbScholarship.getId() + "-" + majorId + "-" + graderId);
            if (s != null){
                res.add(new ScholarShipLimit(tbScholarship.getId(), tbScholarship.getName(), s));
                continue;
            }
            res.add(new ScholarShipLimit(tbScholarship.getId(), tbScholarship.getName(), 0));
            redisTemplate.opsForValue().set("scholarshipId-majorId-gradeId:" + tbScholarship.getId() + "-" + majorId + "-" + graderId, 0);
        }
        return res;
    }
}
